<!--#include file="clear.asp"-->
<%

'===============================主体功能模块说明===================================
'服务器与客户端接口
'各table作用
'chatroom记录所有房间信息
'roomSayid记录某房间中所有对话内容
'roomTalkersMsg+id记录某房间所有加入者信息
'==============================================================================
%>
<%
'判断输入的命令CMD
If request("CMD")<>"" then
dealCMD(trim(request("CMD")))
Else
response.write("NullCMD")
End If

%>
<%
'-------------------------------函数调用块-------------------------------------
Function dealCMD(command)
'根据不同命令，选择不同处理方法（过程）
 Select case command
   case "INITIALIZE"
   call initialize
   case "CREATE"
   call createRoom
   case "LOGIN"
   call loginRoom
   case "LOGOUT"
   call userOut
   case "EXITROOM"
   call creatorOut
   case "TALK"
   call talk
   case "REFRESH"
   call refreshTalk
 End Select
End Function

Function getRekey()
'随机获得密钥，为该房间通信所必需
dim key(24)
dim skey
randomize
for i=0 to 23
n=cint(225*rnd)
if n>15 then
key(i)="0x"&cStr(hex(n))
else
key(i)="0x"&"0"&cStr(hex(n))
end if
next
skey=""
for i=0 to 23
skey=skey&key(i)&","
next
getReKey=skey   '返回获取的加密密匙
End Function

Function ss(content)
'将一个字符串content格式如{a,b,c}转化为一个字符串数组
gs=split(content,",")
gs(0)=replace(gs(0),"{","")
gs(UBound(gs))=replace(gs(UBound(gs)),"}","")
ss=gs
End Function

%>

<%
'-------------------------过程调用块-----------------------
Sub initialize
'功能：连接初始化
'接口数据
'请求数据：CMD=INITIALIZE
'返回数据：{creator,createtime,roomname,status,remarks}
set rs=server.createobject("adodb.recordset")
sql="select * from chatroom order by ID desc"
rs.open sql,conn,1,3
while not rs.eof
response.write("{"+rs("creator")+","+rs("createtime")+","+rs("roomname")+","+rs("status")+","+rs("remarks")+"},")
rs.movenext
wend
rs.close
set rs=nothing
End Sub


Sub createRoom
'功能：
'1、对提交的新建房间信息进行处理(对content内容)，在roomChat表中记录相应的信息
'2、分配房间，根据房间编号建立新表，用于记录聊天所有内容和房间所有登陆用户的信息
'3、生成统一的加密钥匙ekey，用于分配到客户端进行加密，同时将创建的密匙发送给创建者
'接口数据
'请求数据：CMD=CREATE&content={roomname,password,creator,remarks,status}
'返回数据：true|ekey
Dim msg
Dim ID
dim maxRoomid
maxRoomid=10   '规定房间最大数量

'使用以下分割函数替代
msg=ss(request("content"))
set rs0=server.createobject("adodb.recordset")
'以下确保房间名无重复，重复即跳出，并返回错误信息
sql0="select * from chatroom where roomname='"+trim(Msg(0))+"'"
'response.write sql0
rs0.open sql0,conn,1,3
if rs0.recordcount>0 then
response.write("room name repeated!")
exit Sub
end if
rs0.close


'以下确保开发数量不大于房间总数
set rs=server.createobject("adodb.recordset")
sql="select * from chatroom"
rs.open sql,conn,1,3
'rs.movelast
'response.write rs.recordcount

'如果是空表情况将如何

'如果不是空表情况
if rs.recordcount<maxRoomid then
if rs.eof and rs.bof then
ID=1
else
rs.movelast
ID=cint(rs("ID"))+1
end if
rs.addnew
'增加房间记录
dim ctime
ctime=now
roomEkey=getRekey()
rs("ekey")=roomEkey               '随机获取加密钥匙
rs("createtime")=ctime
rs("roomname")=trim(Msg(0))
rs("password")=trim(Msg(1))
rs("creator")=trim(Msg(2))
rs("remarks")=trim(Msg(3))
rs("status")=trim(Msg(4))
rs("ID")=ID
'ID=rs("ID")
rs.update

response.write("true|"+roomEkey)   '｜前为CMD明文返回结果，值表示房间创建成功，并返回房间的密钥

'创建新表，表的名字为roomSay+id，用于记录交谈内容，注：所有交谈内容均以密文形式保存到数据库
'新表字段：[sayid]主控键，[say_content]说话内容，以密文存，[say_time]说话时间,[talker]说话人

dim mytableSay
mytableSay="roomSay"&ID  '找到id号后添加


csql="create table "+mytableSay+"(sayid integer primary key,say_content char(200),say_time char(50),talker char(20))"
'response.write csql
conn.execute(csql)


'创建新表，表的名字为roomTalkersMsg+id,记录对话参与者的基本信息。注：用户所有行为特征记录均以明文形式
'新表字段：[talkerid]主控键，[login_name]登陆用户名字，[login_time]登陆时间，[exit_time]离开时间，[room_id]登陆房间的id，[isCreator]是否为创建者
'创建第一条记录，将房主作为房间成员增加信息
dim talkersMsg
talkersMsg="roomTalkersMsg"&ID
msql="create table "+talkersMsg+"(talkerid integer primary key,login_name char(50),login_time char(50),exit_time char(50),room_id integer,isCreator char(5))"
conn.execute(msql)
msql1="insert into "&talkersMsg&"(talkerid,login_name,login_time,room_id,isCreator) values(1,'"&trim(Msg(2))&"','"&ctime&"','"&ID&"',true)"
conn.execute(msql1)
else
response.Write("false|rooms number limited")    '控制房间资源数量
end if 

rs.close
set rs=nothing
conn.close
set conn=nothing
End Sub

Sub loginRoom
'功能：
'1、验证登陆(roomid、password)，将成功登陆的人员信息添加到talkersMsg中
'2、将房间公用ekey分配给用户
'3、增加一条房间提示某某用户成功登入的欢迎信息记录(根据登陆成功信息由客户端显示)
'接口数据
'请求数据：CMD=LOGIN&content={roomid,password,loginName}
'返回数据：登陆成功，返回clientName+success logined!|+ekey,否则返回fail
dim roomid
dim password
dim clientName
dim ekey
dim content

contents=ss(request("content"))
roomid=cint(trim(contents(0)))
'response.write roomid
password=trim(contents(1))
'response.write password
clientName=trim(contents(2))
'response.write clientName
'1、登陆认证-----------------------------
set rs=server.createobject("adodb.recordset")
sql="select * from chatroom where password='"+password+"' and ID="&roomid
'response.write sql
rs.open sql,conn,1,2
if not rs.eof  then
msgTableName="roomTalkersMsg"&roomid
ekey=rs("ekey")
'response.write ekey
else
response.write("fail")
exit Sub
end if
rs.close
set rs=nothing
'-------------------------------------以上完成密码验证及获取ekey
'2、注册登陆信息--------------------------------
set rs1=server.createobject("adodb.recordset")
sql1="select * from "&msgTableName
'response.write sql1
rs1.open sql1,conn,1,3

dim talkerid
if rs1.eof and rs1.bof then
talkerid=1
else
rs1.movelast
talkerid=1+rs1("talkerid")
end if
rs1.addnew
'response.write talkerid
rs1("login_name")=clientName
rs1("talkerid")=talkerid
rs1("login_time")=now
rs1("room_id")=roomid
rs1("isCreator")="0"
rs1.update
'response.write talkerid
rs1.close
set rs1=nothing
response.write(clientName+" success logined!|"+ekey)
'----------------------------注册完毕
End Sub

Sub userOut
'功能：普通用户退出房间
'接口数据
'请求信息：CMD=LOGOUT&content={roomid,talker}
'返回信息：user logout success!
End Sub

Sub creatorOut
'房间创建者退出房间
call clsRoom
End Sub

Sub talk
'功能：
'1、将说话内容写入数据库表roomSay中
'接口数据
'请求信息：CMD=TALK&content={roomid,talker,talkcontent}，其中talkcontent为加密内容。
'返回信息：add say_content success!
dim talk_content
dim talker
dim roomid
dim sayTabName
dim sayid
dim stime
dim contents
contents=ss(request("content"))
roomid=cInt(trim(contents(0)))
'response.write roomid
sayTabName="roomSay"&roomid
talker=trim(contents(1))
talk_content=trim(contents(2))
stime=now
'sql="insert into "&sayTabName&"(sayid,say_content,say_time,talker) values(2,'"&talk_content&"','"&stime&"','"&talker&"')"
'response.write sql
'conn.execute(sql)
set rs=server.createobject("adodb.recordset")
sql="select * from "&sayTabName
'response.write sql
rs.open sql,conn,1,3
'response.write rs("content")

if rs.eof and rs.bof then
sayid=1
else
rs.movelast
sayid=1+rs("sayid")
end if
rs.addnew
rs("sayid")=sayid
rs("say_content")=talk_content
rs("say_time")=stime
rs("talker")=talker
rs.update
response.write("add say_content success!")
rs.close
set rs=nothing
End Sub

Sub refreshTalk
'功能：从数据库定时调取数据，以更新说话内容
'接口数据
'请求数据：CMD=REFRESH&content=roomid
'返回数据：{talker,say_time,say_content},{...}
dim roomid
dim sayTabName
roomid=cInt(request("content"))
sayTabName="roomSay"&roomid
set rs=server.createobject("adodb.recordset")
sql="select * from "&sayTabName&" order by sayid desc"
rs.open sql,conn,1,2
while not rs.eof
response.write("{"&rs("talker")&","&rs("say_time")&","&rs("say_content")&"},")
rs.movenext
wend
End Sub
%>